﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Landpy.CruiseControlNet.FacadeInterface.SerializerModule;
using Landpy.CruiseControlNet.Infrastructure.Aop.WrapAttribute;

namespace Landpy.CruiseControlNet.DomainLayer.SerializerModule
{
    public class Serializer<TSerialize> : ISerializer<TSerialize> where TSerialize : class
    {
        [NotThrowException]
        [ExceptionMessageBox]
        [LogException]
        public string Serialize(TSerialize serializeObject)
        {
            var serializedString = new StringBuilder();
            var serializer = new XmlSerializer(typeof(TSerialize));
            using (var writer = new StringWriter(serializedString))
            {
                serializer.Serialize(writer, serializeObject, this.GetEmptyXmlSerializerNamespaces());
            }
            return serializedString.ToString();
        }

        [NotThrowException]
        [ExceptionMessageBox]
        [LogException]
        public TSerialize DeSerialize(string serializedString)
        {
            TSerialize serializeObject;
            if (String.IsNullOrEmpty(serializedString))
            {
                return default(TSerialize);
            }
            var serializer = new XmlSerializer(typeof(TSerialize));
            using (var reader = new StringReader(serializedString))
            {
                serializeObject = serializer.Deserialize(reader) as TSerialize;
            }
            return serializeObject;
        }

        [NotThrowException]
        [ExceptionMessageBox]
        [LogException]
        public TSerialize DeSerializeFile(string filePath)
        {
            TSerialize serializeObject;
            using (TextReader textReader = new StreamReader(filePath))
            {
                serializeObject = this.DeSerialize(textReader.ReadToEnd());
            }
            return serializeObject;
        }

        private XmlSerializerNamespaces GetEmptyXmlSerializerNamespaces()
        {
            var xmlSerializerNamespaces = new XmlSerializerNamespaces();
            xmlSerializerNamespaces.Add(String.Empty, String.Empty);
            return xmlSerializerNamespaces;
        }
    }
}
